package inset;

import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

import org.jgraph.JGraph;
import org.jgraph.graph.AttributeMap;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
import org.jgrapht.ext.IntegerNameProvider;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultDirectedWeightedGraph;
import org.jgrapht.graph.DefaultWeightedEdge;

public class GraphViewer extends JFrame
{
    public GraphViewer(String title, DefaultDirectedWeightedGraph<Point2D, DefaultWeightedEdge> g)
    {
    super(title);    
	JGraphModelAdapter<Point2D, DefaultWeightedEdge> adapter = new JGraphModelAdapter<Point2D, DefaultWeightedEdge>(g, new AttributeMap(), new AttributeMap(), new CellFactory(g));
	
	getContentPane().add(new JScrollPane(new JGraph(adapter)));
	
	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	
	pack();
	setVisible(true);
    }
    
    public IntegerNameProvider<Point2D> getNamer()
    {
	return namer;
    }
    
    class CellFactory implements org.jgrapht.ext.JGraphModelAdapter.CellFactory<Point2D, DefaultWeightedEdge>
    {	
	public CellFactory(DefaultDirectedWeightedGraph<Point2D, DefaultWeightedEdge> g)
	{
	    this.g = g;
	}
	
	public DefaultGraphCell createVertexCell(Point2D jGraphTVertex)
	{   
	    DefaultGraphCell cell = new DefaultGraphCell(namer.getVertexName(jGraphTVertex));
	    //DefaultGraphCell cell = new DefaultGraphCell("");
	    
	    AttributeMap attr = new AttributeMap();
	    GraphConstants.setBounds(attr, new Rectangle2D.Double(jGraphTVertex.getX() * scaleFactor + trans, jGraphTVertex.getY() * scaleFactor + trans, 20, 10));	    
	    
	    cell.setAttributes(attr);
	    
	    return cell;
	}

	public org.jgraph.graph.DefaultEdge createEdgeCell(DefaultWeightedEdge jGraphTEdge)
	{
	    org.jgraph.graph.DefaultEdge edge = new org.jgraph.graph.DefaultEdge();
	    
	    AttributeMap attr = new AttributeMap();
	    GraphConstants.setLineEnd(attr, GraphConstants.ARROW_TECHNICAL);
            GraphConstants.setEndFill(attr, true);
            GraphConstants.setEndSize(attr, 5);
            GraphConstants.setLineWidth(attr, (float)( g.getEdgeWeight(jGraphTEdge) + 1.0) );
            
            edge.setAttributes(attr);
	    
	    return edge;
	}
	
	DefaultDirectedWeightedGraph<Point2D, DefaultWeightedEdge> g;
    }
    
    private int trans = 40;
    private int scaleFactor = 50;
    private IntegerNameProvider<Point2D> namer = new IntegerNameProvider<Point2D>();
}
